//
//  TGMModel2CollectionViewAdapter.m
//  TravelGuideHD
//
//  Created by xiaofeng on 14-9-2.
//  Copyright (c) 2014年 mafengo Inc. All rights reserved.
//

#import "TGMModel2CollectionViewAdapter.h"
#import "TGMDefaultActivityPullToRefreshView.h"

#define RefreshHeaderViewTag    1111
@interface TGMModel2CollectionViewAdapter() <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout >
{
    
}
@end

@implementation TGMModel2CollectionViewAdapter
- (id)init
{
    self = [super init];
    if (self)
    {
        _initOffsetY = OFFSETY_UNKNOW;
        _refreshLoading = NO;
        _refreshError   = NO;
        _hasBinded = NO;
        
//        _getMoreCell = [[TGMCollectionViewMoreCell alloc] initWithFrame:CGRectZero];
//        _emptyCell  = [[TGMCollectionViewEmptyCell alloc] initWithFrame:CGRectZero];
        
        // TODO: 增加接口
//        _emptyCell.emptyImage = [UIImage imageNamed:@"re_load"];
        
//        if (IS_IPAD)
//        {
//            self.emptyContentImage = [UIImage imageNamed:@"img_nodownload"];
//        }
//        else
//        {
//            self.emptyContentImage = [UIImage imageNamed:@"re_load"];
//        }
        
    }
    return self;
}

- (void)buildListData
{
    self.listData = [_model listModelItemForDataId:_actionData.dataId];
}

- (BOOL)shouldUseFestalRefreshHeader
{
    return NO;
}

- (BOOL)hasBinded
{
    return _collectionView && _hasBinded;
}


- (void)registerInnerSupplementaryCells:(UICollectionView*)collectionView;
{
    [collectionView registerClass:[TGMCollectionViewMoreCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"get_more"];
    [collectionView registerClass:[TGMCollectionViewEmptyCell class] forCellWithReuseIdentifier:@"empty"];
}

- (void)registerCollectionViewCells:(UICollectionView*)collectionView;
{
    
}

- (void)bindCollectionView:(UICollectionView*)collectionView
                 withModel:(TGMBaseModel*)model
                actionData:(TGMBaseModelActionData*)actionData
                 atOffsetY:(int)initOffsetY;
{
    NSAssert([NSThread isMainThread], @"MUST BIND IN MAIN THREAD!!!");
    
    _hasBinded = YES;
    _collectionView = collectionView;
    _scrollView = collectionView;
    _model = model;
    _actionData = actionData;
    _initOffsetY = initOffsetY;
    
    collectionView.alwaysBounceVertical = YES;
    
    [[model class] addDataObserver:self];
    
    UIView *headerView = [_collectionView viewWithTag:RefreshHeaderViewTag];
    if (headerView)
    {
        [headerView removeFromSuperview];
    }
    
    [self buildListData];
    
    [self registerInnerSupplementaryCells:collectionView];
    
    [self registerCollectionViewCells:collectionView];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.contentInset = [self contextScrollViewContentInset];
    
    [self cleanPullToRefreshFacadeStyle];
    if ([self supportPullRefreshHeader])
    {
        [self requirePullToRefreshFacadeStyle];
    }
    
    if (initOffsetY == OFFSETY_UNKNOW )
    {
        if ([self shouldModelInitRefresh])
        {
            _refreshLoading = YES;
            [self triggerRefresh];
        }
        else
        {
            UIEdgeInsets inset = [self contextScrollViewContentInset];
            [_collectionView setContentOffset:CGPointMake(0, -inset.top)];
        }
    }
    else
    {
        CGPoint contentOffset = CGPointMake(0, initOffsetY);
        [_collectionView setContentOffset:contentOffset animated:NO];
    }
    [_collectionView reloadData];
}

- (void)bindCollectionView:(UICollectionView*)collectionView
                 withModel:(TGMBaseModel*)model
                actionData:(TGMBaseModelActionData*)actionData
                 atOffsetY:(int)initOffsetY
                emptyImage:(UIImage*)emptyImage
                 emptyText:(NSString*)emptyText
{
    self.emptyContentText = emptyText;
    self.emptyContentImage = emptyImage;
    [self bindCollectionView:collectionView withModel:model actionData:actionData atOffsetY:initOffsetY];
}

- (UIEdgeInsets)contextScrollViewContentInset
{
    if ([self.delegate respondsToSelector:@selector(adapter:scrollContentInset:)])
    {
        return [self.delegate adapter:self scrollContentInset:_collectionView];
    }
    else
    {
        return UIEdgeInsetsMake(self.contextViewController.topLayoutGuide.length,
                                0,
                                self.contextViewController.bottomLayoutGuide.length,
                                0);
    }
}

- (int)markedContentOffsetYOfTableView;
{
    if (_refreshLoading)
    {
        return OFFSETY_UNKNOW;
    }
    else
    {
        return _collectionView.contentOffset.y;
    }
}

- (BOOL)isRefreshLoading
{
    return _refreshLoading && self.currentOperationTask && self.currentOperationTask.dataRequestType == kMFWDataRequest_Refresh;
}

- (void)dealloc
{
    if (_collectionView.delegate == self)
    {
        _collectionView.delegate = nil;
    }
    if (_collectionView.dataSource == self)
    {
        _collectionView.dataSource = nil;
    }

    [[_model class] removeDataObserver:self];
    if (self.currentOperationTask)
    {
        [self.currentOperationTask cancel];
        self.currentOperationTask = nil;
    }
}

- (void)requestRefresh
{
    [super requestRefresh];
    
    if (self.currentOperationTask)
    {
        _emptyCell.state = EmptyCellState_Loading;
    }
    
    [_collectionView reloadData];
}

- (void)requestGetMore
{
    [super requestGetMore];
    
    if (self.currentOperationTask)
    {
        [_getMoreCell setInfoText:@"正在加载更多..." forState:MoreCellState_Loading];
    }
}

- (void)reloadUIData:(BOOL)refreshed byRequestType:(MFWDataRequestType)type
{
    if (type == kMFWDataRequest_Refresh)
    {
        if (refreshed)
        {
            [self buildListData];
            [_collectionView reloadData];
        }
        else
        {
            [_collectionView reloadData];
        }
    }
    else if (type == kMFWDataREquest_GetMore)
    {
        if (refreshed)
        {
            [_getMoreCell setInfoText:@"查看更多" forState:MoreCellState_Information];
            [_collectionView reloadData];
        }
        else
        {
            [_getMoreCell setInfoText:@"加载更多失败，点击查看更多" forState:MoreCellState_Information];
        }
    }
}

- (MFWTask*)startRefreshRequest
{
    TGMBaseModelActionData *actionData = [self actionDataForRequestModelData:kMFWDataRequest_Refresh];
    return [self.model requestRefresh:actionData];
}

- (MFWTask*)startGetMoreRequest
{
    TGMBaseModelActionData *actionData = [self actionDataForRequestModelData:kMFWDataREquest_GetMore];
    return [self.model requestGetMore:actionData];
}

- (BOOL)supportPullRefreshHeader
{
    return NO;
}

- (BOOL)supportGetMoreFooter
{
    return NO;
}

- (BOOL)shouldModelInitRefresh;//default return YES
{
    return [self.model needRefreshForDataId:_actionData.dataId];
}

- (BOOL)hasMoreData;
{
    return [self.model canGetMoreForDataId:_actionData.dataId];
}

// 此函数里设置内容为空的时候的cell样式，一般都是修改空的时候的图片
- (void)willShowEmptyContentCell;
{
    if (_refreshError)
    {
        _emptyCell.state = EmptyCellState_Error;

        // to setting tip image
    }
    else
    {
        if (_emptyCell.emptyImage == nil)
        {
            _emptyCell.emptyImage = self.emptyContentImage;
        }
        if (self.emptyContentText != nil && self.emptyContentText.length != 0)
        {
            _emptyCell.emptyText = self.emptyContentText;
        }
        _emptyCell.state = EmptyCellState_Tips;

        // to setting tip image & text
    }
}

#pragma mark - UICollectionViewDelegate
- (void)model2CollectionView:(UICollectionView*)collectionView didSelectItemAtIndexPath:(NSIndexPath*)indexPath;
{
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{

    BOOL handled = NO;
    if ([self.listData count] == 0)
    {
        [self triggerRefresh];
        return;
    }
    
    if ([self.delegate respondsToSelector:@selector(adapter:collectionView:didSelectItemAtIndexPath:)])
    {
        handled = [self.delegate adapter:self collectionView:collectionView didSelectItemAtIndexPath:indexPath];
    }
    
    if (!handled)
    {
        [self model2CollectionView:collectionView didSelectItemAtIndexPath:indexPath];
    }
}

#pragma mark - TGMCollectionViewMoreCellDelegate
- (void)collectionViewMoreCellDidSelected:(TGMCollectionViewMoreCell*)moreCell;
{
    if (moreCell.state != MoreCellState_Loading)
    {
        [self requestGetMore];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    int count = [self.listData count];
    if (count == 0)
    {// empty
        CGSize si = CGSizeMake(collectionView.boundsWidth,
                               collectionView.boundsHeight - collectionView.contentInset.top - collectionView.contentInset.bottom);
        return si;
    }
    else if ([self supportGetMoreFooter] && [self hasMoreData] && indexPath.section == [self numberOfSectionsInCollectionView:collectionView] - 1)
    {// get more
        DLog(@"!!!!!!!!!!!!!!!!!!!!! warningggggggg");
        return CGSizeZero;
    }
    else if ([self respondsToSelector:@selector(model2CollectionView:layout:sizeForItemAtIndexPath:)])
    {
        return [self model2CollectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:indexPath];
    }
    else
    {
        return ((UICollectionViewFlowLayout*)collectionViewLayout).itemSize;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
{
    int count = [self.listData count];
    if (count == 0)
    {
        return CGSizeMake(1, 0);
    }
    
    if (count > 0 && [self supportGetMoreFooter] && [self hasMoreData] && section == [self numberOfSectionsInCollectionView:collectionView] - 1) {
        return CGSizeMake(collectionView.boundsWidth, Collection_More_Cell_Height);
    }
    
    if ([self respondsToSelector:@selector(model2CollectionView:layout:referenceSizeForHeaderInSection:)])
    {
        return [self model2CollectionView:collectionView layout:collectionViewLayout referenceSizeForHeaderInSection:section];
    }
    else
    {
        return ((UICollectionViewFlowLayout*)collectionViewLayout).headerReferenceSize;
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
{
    int count = [self.listData count];
    if (count == 0)
    {
        return UIEdgeInsetsZero;
    }
    if ([self respondsToSelector:@selector(model2CollectionView:layout:insetForSectionAtIndex:)])
    {
        return [self model2CollectionView:collectionView layout:collectionViewLayout insetForSectionAtIndex:section];
    }
    else
    {
        return ((UICollectionViewFlowLayout*)collectionViewLayout).sectionInset;
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
{
    if ([self respondsToSelector:@selector(model2CollectionView:layout:minimumLineSpacingForSectionAtIndex:)])
    {
        return [self model2CollectionView:collectionView layout:collectionViewLayout minimumLineSpacingForSectionAtIndex:section];
    }
    else
    {
        return ((UICollectionViewFlowLayout*)collectionViewLayout).minimumLineSpacing;
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;
{
    if ([self respondsToSelector:@selector(model2CollectionView:layout:minimumInteritemSpacingForSectionAtIndex:)])
    {
        return [self model2CollectionView:collectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
    }
    else
    {
        return ((UICollectionViewFlowLayout*)collectionViewLayout).minimumInteritemSpacing;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;
{
    if ([self respondsToSelector:@selector(model2CollectionView:layout:referenceSizeForFooterInSection:)])
    {
        return [self model2CollectionView:collectionView layout:collectionViewLayout referenceSizeForFooterInSection:section];
    }
    else
    {
        return ((UICollectionViewFlowLayout*)collectionViewLayout).footerReferenceSize;
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
{
    int count = [self.listData count];
    if (count == 0)
    {
        if (_refreshLoading)
        {
            if (![self supportPullRefreshHeader])
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 1;
        }
    }
    else if (count > 0 && [self supportGetMoreFooter] && [self hasMoreData]
        && section == [self numberOfSectionsInCollectionView:collectionView] - 1)
    {
        return 0;
    }
    else
    {
        return [self model2CollectionView:collectionView numberOfItemsInSection:section];
    }
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    int count = [self.listData count];
    if (count == 0)
    {// empyt
        _emptyCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"empty" forIndexPath:indexPath];
        
        /** add by xiangguang at 2014-11-19 扩展emptyCell宽度到collectionView的宽度 begin **/
        [_emptyCell setFrameWidth: collectionView.boundsWidth];
        /** end */
        
        if (_refreshLoading)
        {
            if (![self supportPullRefreshHeader])
            {
                _emptyCell.state = EmptyCellState_Loading;
                return _emptyCell;
            }
        }
        else if (!_refreshLoading)
        {
            if (_refreshError)
            {
                _emptyCell.state = EmptyCellState_Error;
            }
            else
            {
                _emptyCell.state = EmptyCellState_Tips;
            }
            
            [self willShowEmptyContentCell];
            return _emptyCell;
        }
    }
    else if ([self supportGetMoreFooter] && [self hasMoreData] && indexPath.section == [self numberOfSectionsInCollectionView:collectionView] - 1)
    {// get more
        
    }
    else
    {
        return [self model2CollectionView:collectionView cellForItemAtIndexPath:indexPath];
    }
    return nil;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;
{
    int count = [self.listData count];
    
    NSInteger numberOfSections = 0;
    if (count == 0)
    {
        numberOfSections = 1;
    }
    else
    {
        numberOfSections = [self model2CollectionNumberOfSectionsInCollectionView:collectionView];
        if (count > 0 && [self supportGetMoreFooter] && [self hasMoreData])
        {
            numberOfSections++;
        }
    }
    return numberOfSections;
}

// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
{
    int count = [self.listData count];
    if (count > 0 && [self supportGetMoreFooter] && [self hasMoreData]
        && indexPath.section == [self numberOfSectionsInCollectionView:collectionView] - 1)
    {
        _getMoreCell = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"get_more" forIndexPath:indexPath];
        [_getMoreCell setInfoText:@"查看更多" forState:MoreCellState_Information];
        _getMoreCell.delegate = self;
        return _getMoreCell;
    }
    else
    {
        return [self model2CollectionView:collectionView viewForSupplementaryElementOfKind:kind atIndexPath:indexPath];
    }
}

#pragma mark - Model2UIDataSource

- (NSInteger)model2CollectionNumberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionReusableView *)model2CollectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (NSInteger)model2CollectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [[self listData] count];
}

- (UICollectionViewCell *)model2CollectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    return nil;
}

#pragma mark - #pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    // @override
    [super scrollViewDidScroll:scrollView];
}

// called on start of dragging (may require some time and or distance to move)
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
{
    
}

// called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
{
    
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView;   // called on finger up as we are moving
{
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;      // called when scroll view grinds to a halt
{
    // @override
    [super scrollViewDidEndDecelerating:scrollView];
    
    if ([self supportGetMoreFooter] && [self hasMoreData] && [_getMoreCell superview])
    {
        CGRect rc = _getMoreCell.frame;
        if(scrollView.contentOffset.y + scrollView.frame.size.height - rc.origin.y
           >= (rc.size.height * 0.8))
        {
            [self performSelector:@selector(requestGetMore) withObject:nil afterDelay:0.0f];
        }
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;
{
    
}

@end
